"""
内容生成API路由
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel

from ..core.database import get_db, HotTrend, GeneratedContent
from ..core.logger import app_logger
from ..core.config import get_settings
from ..generators.openai_generator import OpenAIGenerator
from ..generators.qwen_generator import QwenGenerator

settings = get_settings()

router = APIRouter()


class GenerateContentRequest(BaseModel):
    """生成内容请求模型"""
    trend_id: int
    platforms: List[str]  # weibo, twitter, wechat
    style: Optional[str] = "default"  # default, formal, casual, humorous
    generator: Optional[str] = "qwen"  # openai, qwen


@router.post("/generate", summary="生成内容")
async def generate_content(
    request: GenerateContentRequest,
    db: Session = Depends(get_db)
):
    """基于热点生成适合不同平台的内容"""
    
    # 获取热点信息
    trend = db.query(HotTrend).filter(HotTrend.id == request.trend_id).first()
    if not trend:
        raise HTTPException(status_code=404, detail="热点不存在")
    
    results = {}
    
    # 选择生成器
    if request.generator == "qwen" and settings.QWEN_API_KEY:
        generator = QwenGenerator()
    else:
        generator = OpenAIGenerator()
    
    for platform in request.platforms:
        try:
            # 使用AI生成器生成内容
            trend_data = {
                "title": trend.title,
                "description": trend.description,
                "source": trend.source,
                "url": trend.url
            }
            content = await generator.generate(trend_data, platform, request.style)
            
            # 保存生成的内容
            generated = GeneratedContent(
                trend_id=request.trend_id,
                platform=platform,
                content=content["text"],
                hashtags=content.get("hashtags", "")
            )
            db.add(generated)
            
            results[platform] = {
                "status": "success",
                "content": content
            }
            
        except Exception as e:
            app_logger.error(f"为平台 {platform} 生成内容失败: {str(e)}")
            results[platform] = {
                "status": "error",
                "message": str(e)
            }
    
    db.commit()
    
    return {
        "status": "completed",
        "trend": {
            "id": trend.id,
            "title": trend.title,
            "source": trend.source
        },
        "results": results
    }


async def _generate_platform_content(trend, platform: str, style: str):
    """为特定平台生成内容"""
    
    # 模拟AI生成的内容
    content_templates = {
        "weibo": {
            "text": f"🔥 {trend.title}\n\n{trend.description or '这个话题很有意思，值得关注！'}\n\n#热点 #AI推荐",
            "hashtags": "#热点 #AI推荐"
        },
        "twitter": {
            "text": f"🚀 {trend.title}\n\n{trend.description or 'Interesting topic worth following!'}\n\n#trending #AI",
            "hashtags": "#trending #AI"
        },
        "wechat": {
            "text": f"【热点关注】{trend.title}\n\n{trend.description or '这是一个值得关注的热门话题，让我们一起来了解一下。'}\n\n我们将持续关注相关动态，为您带来最新资讯。",
            "hashtags": ""
        }
    }
    
    return content_templates.get(platform, content_templates["weibo"])


@router.get("/", summary="获取生成的内容列表")
async def get_generated_contents(
    platform: Optional[str] = None,
    status: Optional[str] = None,
    limit: int = 20,
    db: Session = Depends(get_db)
):
    """获取已生成的内容列表"""
    
    query = db.query(GeneratedContent)
    
    if platform:
        query = query.filter(GeneratedContent.platform == platform)
    
    if status:
        query = query.filter(GeneratedContent.status == status)
    
    contents = query.order_by(GeneratedContent.created_at.desc()).limit(limit).all()
    
    return {
        "status": "success",
        "data": [
            {
                "id": content.id,
                "trend_id": content.trend_id,
                "platform": content.platform,
                "content": content.content,
                "hashtags": content.hashtags,
                "status": content.status,
                "created_at": content.created_at.isoformat()
            }
            for content in contents
        ],
        "total": len(contents)
    }